#!/bin/sh

min_id=$1
max_id=$2

haproxy_node_num=$3

if [ -z "$min_id" ]; then
    min_id=1
fi

if [ -z "$max_id" ]; then
    max_id=3
fi

if [ -z "$haproxy_node_num" ]; then
    haproxy_node_num=1
fi

base_path=`pwd`/..

echo 'min_id='$min_id 'max_id='$max_id 'base_path='$base_path

ip='192.168.2.'
ips=''
servers=''
mysql_port=3307

for id in `seq $min_id $max_id`; do
  let ip_last_num=10+${id}
  ip_tmp=${ip}${ip_last_num}
  if [ -z "${ips}" ]; then
  	ips=${ip_tmp}
  else
  	ips=${ips},${ip_tmp}
  fi

  tmp="server db${id} ${ip_tmp}:${mysql_port} check port 4567 inter 2000 rise 2 fall 5"$'\n\t'
  servers=${servers}${tmp}
  
done

for id in `seq $min_id $max_id`; do
  path=${base_path}/db_${id}
	
  mkdir -p ${path}/mysql
  mkdir -p ${path}/etc/conf.d

  let ip_last_num=10+${id}

  PORT=${mysql_port} envsubst < ./my.cnf.tmpl > ${path}/etc/my.cnf
  ID=${id} ADDRESS=${ip}${ip_last_num} IPS=${ips} envsubst < ./galera.cnf.tmpl > ${path}/etc/conf.d/galera.cnf

  let port_map=3310+${id}
  ID=${id} IP=${ip}${ip_last_num} PORT=${port_map} envsubst < ./docker-run.sh.tmpl > ${path}/docker-run.sh

  if [ ${id} = 1 ]; then
    ID=${id} IP=${ip}${ip_last_num} PORT=${port_map} envsubst < ./docker-first-node-run.sh.tmpl > ${path}/docker-first-node-run.sh
    chmod +x ${path}/docker-first-node-run.sh
  fi

  chmod +x ${path}/docker-run.sh
done

for haproxy_id in `seq 1 $haproxy_node_num`; do
    path=${base_path}/haproxy_${haproxy_id}
  
    mkdir -p ${path}/etc

    let ip_last_num=100+${haproxy_id}

    let port_map=3305+${haproxy_id}

    ID=${haproxy_id} IP=${ip}${ip_last_num} PORT=${port_map} envsubst < ./haproxy/docker-run.sh.tmpl > ${path}/docker-run.sh

    IP=${ip}${ip_last_num} PORT=${port_map} SERVERS=${servers} envsubst < ./haproxy/haproxy.cfg.tmpl > ${path}/etc/haproxy.cfg

    chmod +x ${path}/docker-run.sh
done